const { trim } = require("./index");
/**
 * 将对象处理成 "where key1=value1 and key2=value2;" 的形式
 * @param {*} target 要处理语句的对象
 * @returns " where key1=value1 and key2=value2;"
 * 用法: whereAnd({ username: "张三" })
 */
function whereAnd(target, option) {
  let _table = option.table.split(",");
  let sql = "",
    count = 0;
  for (let key in target) {
    if (target[key]) {
      target[key] = trim(target[key]); // 字符串收尾去空
      sql += `${count > 0 ? " and" : ""} ${key}='${target[key]}'`;
    }
    count++;
  }
  return sql === "" ? "" : _table.length > 1 ? " and" + sql : " where" + sql;
}

function connectTable(where, option) {
  let _sql = "";
  let _table = option.table.split(",");
  if (_table.length > 1) {
    let _connect = " where";
    _table.forEach((item, index) => {
      _connect += `${index === 0 ? "" : " ="} ${item}.${option.connect}`;
    });
    _sql += _connect;
  }
  if (where) {
    _sql += whereAnd(where, option);
  }
  return _sql;
}

function keyValue(obj) {
  let _str = "",
    count = 0;
  for (let key in obj) {
    _str += `${count > 0 ? "," : ""} ${key}=${obj[key]}`;
    count++;
  }
  return _str;
}

class SQL {
  constructor(option) {
    this.$option = option;
  }
  queryAll(where) {
    let sql = `select * from ${this.$option.table}`;
    return sql + connectTable(where, this.$option) + ";";
  }

  query(where, replacer = "") {
    let sql = `select * from ${this.$option.table}`;
    if (replacer) {
      if (typeof replacer === "object") {
        replacer = replacer.join(",");
      }
      sql = `select ${replacer} from ${this.$option.table}`;
      return sql + connectTable(where, this.$option) + ";";
    } else {
      return this.queryAll(where);
    }
  }

  add(table = this.$option.table) {
    return `insert into ${table} set ?` + ";";
  }

  edit(params, where, table = this.$option.table) {
    return (
      `update ${table} set ${keyValue(params)}${whereAnd(where, {
        table,
      })}` + ";"
    );
  }

  delete(where, table = this.$option.table) {
    return `delete from ${table}${whereAnd(where, { table })}` + ";";
  }
}

/**
 * 使用
 */
// let params = {
//   table: "user,dept",
//   connect: "dept_id",
// };
// let sql = new SQL(params);
// console.log(sql.queryAll({ user_name: "白敬亭", user_age: "25" }));
// console.log(sql.queryAll());
// console.log(sql.query());
// console.log(
//   sql.query({ user_name: "白敬亭", user_age: "25" }, "user_name,user_id")
// );
// console.log(sql.add("user"));
// console.log(
//   sql.edit(
//     { user_id: 2021001 },
//     { password: "123456", user_sex: 1, user_age: 19 },
//     "user"
//   )
// );
// console.log(sql.delete({ course_id: "1" }, "course"));

module.exports = {
  whereAnd,
  SQL,
};
